package com.fbs.job.admin.core.complete;

import com.fbs.job.admin.core.config.FbsJobAdminConfig;
import com.fbs.job.admin.core.entity.FbsJobInfo;
import com.fbs.job.admin.core.entity.FbsJobLog;
import com.fbs.job.admin.core.enums.TriggerTypeEnum;
import com.fbs.job.admin.core.thread.JobTriggerPoolHelper;
import com.fbs.job.core.context.FbsJobContext;
import com.fbs.job.core.model.ResultT;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.text.MessageFormat;

/**
 * @author wwd 2024-02-10 20:43:10
 */
public class FbsJobCompleter {
    private static Logger logger = LoggerFactory.getLogger(FbsJobCompleter.class);

    /**
     * common fresh handle entrance (limit only once)
     *
     * @param fbsJobLog
     * @return
     */
    public static int updateHandleInfoAndFinish(FbsJobLog fbsJobLog) {

        // finish
        finishJob(fbsJobLog);

        // text最大64kb 避免长度过长
        if (fbsJobLog.getHandleMsg().length() > 15000) {
            fbsJobLog.setHandleMsg( fbsJobLog.getHandleMsg().substring(0, 15000) );
        }

        // fresh handle
        return FbsJobAdminConfig.getAdminConfig().getFbsJobLogMapper().updateHandleInfo(fbsJobLog);
    }


    /**
     * do somethind to finish job
     */
    private static void finishJob(FbsJobLog fbsJobLog){

        // 1、handle success, to trigger child job
        String triggerChildMsg = null;
        if (FbsJobContext.HANDLE_CODE_SUCCESS == fbsJobLog.getHandleCode()) {
            FbsJobInfo fbsJobInfo = FbsJobAdminConfig.getAdminConfig().getFbsJobInfoMapper().getById(fbsJobLog.getJobId());
            if (fbsJobInfo!=null && fbsJobInfo.getChildJobid()!=null && fbsJobInfo.getChildJobid().trim().length()>0) {
                triggerChildMsg = "<br><br><span style=\"color:#00c0ef;\" > >>>>>>>>>>>"+ "触发子任务" +"<<<<<<<<<<< </span><br>";

                String[] childJobIds = fbsJobInfo.getChildJobid().split(",");
                for (int i = 0; i < childJobIds.length; i++) {
                    int childJobId = (childJobIds[i]!=null && childJobIds[i].trim().length()>0 && isNumeric(childJobIds[i]))?Integer.valueOf(childJobIds[i]):-1;
                    if (childJobId > 0) {

                        JobTriggerPoolHelper.trigger(childJobId, TriggerTypeEnum.PARENT, -1, null, null, null);
                        ResultT<String> triggerChildResult = ResultT.success();

                        // add msg
                        triggerChildMsg += MessageFormat.format("{0}/{1} [任务ID={2}], 触发{3}, 触发备注: {4} <br>",
                                (i+1),
                                childJobIds.length,
                                childJobIds[i],
                                (triggerChildResult.getCode()==ResultT.SUCCESS_CODE?"成功":"失败"),
                                triggerChildResult.getMessage());
                    } else {
                        triggerChildMsg += MessageFormat.format("{0}/{1} [任务ID={2}], 触发失败, 触发备注: 任务ID格式错误 <br>",
                                (i+1),
                                childJobIds.length,
                                childJobIds[i]);
                    }
                }

            }
        }

        if (triggerChildMsg != null) {
            fbsJobLog.setHandleMsg( fbsJobLog.getHandleMsg() + triggerChildMsg );
        }

        // 2、fix_delay trigger next
        // on the way

    }

    private static boolean isNumeric(String str){
        try {
            int result = Integer.valueOf(str);
            return true;
        } catch (NumberFormatException e) {
            return false;
        }
    }

}
